package com.example.tofcamera;

import android.graphics.Bitmap;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;

/**
 * Created by j on 2017/2/25.
 */

public class Frame {
    private byte [] data;

    public Frame(ByteBuffer buffer, int size) {
        if(data==null || data.length!=size)
            data=new byte[size];
        buffer.get(data);
    }

    public Frame(byte[] data) {
        this.data = data;
    }

    public byte[] getData() {
        return data;
    }

    public static void SaveRaw(byte[] data,  String fileName) throws IOException
    {
        FileOutputStream out = new FileOutputStream(fileName);
        out.write(data);
        out.close();
    }

    public static byte[] ReadRaw(String fileName) throws IOException
    {
        byte []data=null;
        FileInputStream out = new FileInputStream(fileName);
        out.read(data);
        out.close();
        return data;
    }

    public void SaveRaw(String fileName) throws IOException
    {
        SaveRaw(data, fileName);
    }

    public static void SaveBitmap(String filePath, Bitmap bmp) throws IOException
    {
        File file = new File(filePath);
        // Open the file.
        OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
        // Save the image file as PNG.
        bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
        out.flush();    // Make sure it is saved to file soon, because we are about to add it to the Gallery.
        out.close();
    }

    public static int[] ToInt(byte []d)
    {
        int[] intGreyBuffer = new int[d.length];
        for(int i=0; i < d.length; i++)
        {
            int greyValue = (int)d[i] & 0xff;
            intGreyBuffer[i] = 0xff000000 | (greyValue << 16) | (greyValue << 8) | greyValue;
        }
        return intGreyBuffer;
    }

    public static Bitmap RawToBitmap(byte []d, int width, int height)
    {
        return Bitmap.createBitmap(ToInt(d), width, height, Bitmap.Config.ARGB_8888);
    }

    public void SaveRawBitmap(String fileName, int width, int height) throws IOException
    {
        SaveBitmap(fileName, RawToBitmap(data, width, height));
    }


}
